package com.gitee.ywj1352.nio;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * @author wenjie.yang on 2019/9/10.
 */
@Slf4j
public class ZeroCopy {

    @Test
    public void zoreCopy() throws Exception {
        String srcFileName = "C:\\Users\\wenjie.yang\\Desktop\\项目\\MSD.png";
        RandomAccessFile srcFile = new RandomAccessFile(srcFileName, "r");
        FileChannel srcFileChannel = srcFile.getChannel();

        String destFileName = "C:\\Users\\wenjie.yang\\Desktop\\项目\\uuu.png";
        RandomAccessFile destFile = new RandomAccessFile(destFileName, "rw");
        FileChannel destFileChannel = destFile.getChannel();

        long position = 0;
        long count = srcFileChannel.size();
        srcFileChannel.transferTo(position, count, destFileChannel);
    }

    @Test
    public void copyFileUsingStream() {
        copyFileUsingStream(new File("C:\\Users\\wenjie.yang\\Desktop\\项目\\MSD.png"),
                new File("C:\\Users\\wenjie.yang\\Desktop\\项目\\uuu.png"));
    }

    public void copyFileUsingStream(File source, File target) {
        try (
                InputStream is = new FileInputStream(source);
                OutputStream os = new FileOutputStream(target)
        ) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } catch (IOException ie) {
        }
    }

    public void copyFileUsingChannel(File source, File target) {
        try (
                FileChannel sourceChannel = new FileInputStream(source).getChannel();
                FileChannel targetChannel = new FileOutputStream(target).getChannel()
        ) {
            targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        } catch (IOException e) {
        }
    }


}
